package com.itheima.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UmsResourceMapper;
import com.itheima.pojo.UmsResource;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 袁鹏
 * @date 2022-10-13-11:39
 */
@DubboService
public class UmsResourceApiImpl implements UmsResourceApi{

    @Autowired
    private UmsResourceMapper umsResourceMapper;


    /**
     * 根据资源id获取资源对象
     */
    @Override
    public List<UmsResource> getById(List<Long> resourceIdList) {
        if(CollUtil.isNotEmpty(resourceIdList)) {
            return umsResourceMapper.selectBatchIds(resourceIdList);
        }else{
            return Collections.emptyList();
        }
    }


    /**
     * 根据资源id获取资源对象
     */
    @Override
    public UmsResource getById(Long resourceId) {
        return umsResourceMapper.selectById(resourceId);
    }


    /**
     * 添加新资源
     */
    @Override
    public void create(UmsResource umsResource) {
        umsResource.setCreateTime(new Date());
        umsResourceMapper.insert(umsResource);
    }


    /**
     * 根据id删除资源
     */
    @Override
    public void delete(Long id) {
        umsResourceMapper.deleteById(id);
    }

    @Override
    public void delete(List<Long> idList) {
        if(CollUtil.isEmpty(idList)) {
            umsResourceMapper.deleteBatchIds(idList);
        }
    }


    /**
     * 分页模糊查询后台资源
     */
    @Override
    public Page<UmsResource> pageList(Integer categoryId, String nameKeyword, String urlKeyword, Integer pageNum, Integer pageSize) {
        Page<UmsResource> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<UmsResource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId != null, UmsResource::getCategoryId, categoryId)
                .like(StrUtil.isNotBlank(nameKeyword), UmsResource::getName, nameKeyword)
                .like(StrUtil.isNotBlank(urlKeyword), UmsResource::getUrl, urlKeyword);
        return umsResourceMapper.selectPage(pageInfo, queryWrapper);
    }


    /**
     * 查询所有后台资源
     */
    @Override
    public List<UmsResource> list() {
        return umsResourceMapper.selectList(null);
    }


    /**
     * 修改后台资源
     */
    @Override
    public void update(UmsResource resource) {
        umsResourceMapper.updateById(resource);
    }


    /**
     * 根据分类id获取资源
     */
    @Override
    public List<UmsResource> getByCategoryId(Long id) {
        LambdaQueryWrapper<UmsResource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsResource::getCategoryId, id);
        return umsResourceMapper.selectList(queryWrapper);
    }
}
